package com.youdianstar.app.ui

import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.common.Extra
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.adapter.BranchPagingAdapter
import com.youdianstar.app.databinding.ActivityBranchListBinding

import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.network.BaseApiPagingObserver
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.widget.adapter.FooterAdapter
import com.youdianstar.app.util.DataAppManager
import kotlinx.coroutines.flow.collectLatest
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: BranchListActivity
 * Author: 82149 Create: 2021/9/29 15:18
 * Changes (from 2021/9/29)
 * --------------------------------------------------
 * description: 网点列表,使用Paging3分页
 * ---------------------------------------------------
 *
 */
class BranchListActivity : BaseActivity<ActivityBranchListBinding, BranchViewModel>() {
    override fun layoutId(): Int = R.layout.activity_branch_list

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): BranchViewModel {
        val model: BranchViewModel by viewModel()
        return model
    }

    private var mBranchPagingAdapter = BranchPagingAdapter(this)
    private val mTableTitle : MutableList<String> = mutableListOf()
    /**
     * 网点类型: 可租借、可归还、全部
     */
    private var typeIndex = 0
    private var searchKey: String = ""
    private var isFirstLoad = false

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this, title = getString(R.string.home_nearbyMerchants), isOPBar = false, showInner = true)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .titleBarMarginTop(mBinding.merchantInner)
            .init()

        mTableTitle.run {
            add(getString(R.string.home_rent_tag))
            add(getString(R.string.home_return_tag))
            add(getString(R.string.home_all))
        }
    }

    override fun initData() {
        super.initData()
        mBinding.run {
            rcBranch.adapter = mBranchPagingAdapter.withLoadStateFooter(FooterAdapter {
                //重新请求
                mBranchPagingAdapter.retry()
            })
            //刷新监听
            swBranch.setOnRefreshListener {
                mBranchPagingAdapter.refresh()
            }
            lifecycleScope.launchWhenCreated {
                mBranchPagingAdapter.loadStateFlow.collectLatest {
                    swBranch.isRefreshing = it.refresh is LoadState.Loading
                }
            }
            //1.读取地图定位点（优先使用Intent传入的坐标，如果没有则使用用户当前位置）
            val localLatLng = DataAppManager.instance.getLocalLatLng()
            val lat = if (intent.hasExtra(Extra.IT_LAT)) intent.getDoubleExtra(Extra.IT_LAT, 0.0) else null
            val lng = if (intent.hasExtra(Extra.IT_LNG)) intent.getDoubleExtra(Extra.IT_LNG, 0.0) else null
            // 如果有有效的坐标，保存到DataAppManager以便后续使用
            if (lat != null && lat != 0.0 && lng != null && lng != 0.0) {
                DataAppManager.instance.saveLocalLatLng(com.google.android.gms.maps.model.LatLng(lat, lng))
            }
            //2.初始化Tablelayout,并加载列表
            isFirstLoad = true
            setTabLayoutSelect()
            loadBranchData("", lat, lng)
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.listEventLiveData.observe(this, object : BaseApiPagingObserver(mBinding.rcBranch){
            override fun onReload(v: View?) {
                loadBranchData("")
            }
        })
    }

    override fun initClickEvent() {
        mBinding.etSearch.addTextChangedListener( object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (StrUtil.isEmpty(s.toString())){
                    loadBranchData("", null, null)
                    try {
                        mBinding.rcBranch.smoothScrollToPosition(0)
                    } catch (e :Exception){
                        e.printStackTrace()
                    }
                }
            }
        })

        mBinding.etSearch.setOnEditorActionListener( object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    val searchStr = mBinding.etSearch.text.toString()
                    if (!StrUtil.isEmpty(searchStr)) {
                        loadBranchData(searchStr, null, null)
                    }
                    hideInputKeyboard(mBinding.etSearch)
                }
                return true
            }
        })

        mBinding.typeTable.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val selectIndex = tab?.position ?:0
                typeIndex = selectIndex
                updateTabSelectView(selectIndex)
                if (!isFirstLoad)
                    loadBranchData("", null, null)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {}

            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }

    private fun updateTabSelectView(position:Int){
        mBinding.typeTable.let { layout->
            val tabCount = layout.tabCount
            for (index in 0 until tabCount){
                val tabItem = layout.getTabAt(index)
                tabItem?.customView?.let {tabView->
                    val tvTabTitle: TextView = tabView.findViewById(R.id.tabText)
                    val tvIndicator: TextView = tabView.findViewById(R.id.tabIndicator)
                    tvTabTitle.setTextColor(getViewColor(this, if (index==position) R.color.color_39404D else R.color.color_66666B))
                    tvIndicator.setBackgroundResource(if (index==position) R.drawable.shape_indicator_on else R.drawable.shape_indicator_off)
                }
            }
        }
    }

    /**
     * 刷新Table layout
     * --初始化设置
     */
    private fun setTabLayoutSelect(){
        mBinding.typeTable.let { layout->
            layout.removeAllTabs()
            for ((index,title) in mTableTitle.withIndex()){
                val tabItem = layout.newTab()
                tabItem.setCustomView(R.layout.layout_tab_merchant)
                tabItem.tag = title
                layout.addTab(tabItem, index==0)
                tabItem.customView?.let { tabView->
                    val tvTabTitle: TextView = tabView.findViewById(R.id.tabText)
                    tvTabTitle.text = title
                }
            }
        }
        mBinding.typeTable.tabMode = TabLayout.MODE_FIXED
        mBinding.typeTable.setScrollPosition(0,0F, false)
        updateTabSelectView(0)
    }

    /**加载网点数据*/
    private fun loadBranchData(search: String, lat: Double? = null, lng: Double? = null) {
        lifecycleScope.launchWhenCreated {
            val dataType = when(typeIndex){
                0-> 1
                1-> 2
                else -> null
            }
            mViewModel.getBranchListData(search, dataType, lat, lng).collectLatest {
                isFirstLoad = false
                mBranchPagingAdapter.submitData(it)
            }
        }
    }
}